import React, {Component} from "react";
import { connect } from 'react-redux';

class Map extends Component {
  constructor(props) {
    super(props);

    const $t = this;
    const points = [];
    let mapEnable = false;

    $t.componentDidMount = () => {
      setTimeout(()=>{
        $t.map = new BMap.Map("map_container");
        $t.map.centerAndZoom(new BMap.Point(104.214, 30.574), 13);
        $t.map.enableScrollWheelZoom();
        mapEnable = true;
      },500);
    };

    $t.componentDidUpdate = ()=>{
      const {wtgprs} = $t.props;
      if(wtgprs && mapEnable){
        const x = wtgprs[25]; const y=wtgprs[26];
        const point = new BMap.Point(x,y);
        points.push(point);

        $t.map.clearOverlays();
        $t.addLine(points);

        $t.movePlane(x,y);
        const  zoom = $t.map.getZoom();
        $t.map.centerAndZoom(point,zoom<16?16:zoom);
      }
    };

    $t.movePlane = (x,y)=>{
      $t.map.addOverlay($t.getPlane(x,y));
    };

    $t.getPlane = (x,y)=>{
      const icon  =new BMap.Symbol(BMap_Symbol_SHAPE_PLANE,{scale: 1, rotation: 0});
      const plane = new BMap.Marker(new BMap.Point(x,y), {icon});
      icon.setFillColor("0xff0000");

      return plane;
    };

    $t.addLine = (points) => {
      const linePoints = []; const pointsLen = points.length; let i; let polyline;
      if (pointsLen !== 0) {
        for (i = 0; i < pointsLen; i++) {
          linePoints.push(new BMap.Point(points[i].lng, points[i].lat));
        }

        polyline = new BMap.Polyline(linePoints, {strokeColor: "red", strokeWeight: 5, strokeOpacity: 0.5});
        $t.map.addOverlay(polyline);
      }
    };

    $t.render = () => {
      return (
        <div id="map_container" />
      )
    }
  }
}


function mapStateToProps({ wtgprs }) {
  return {
    wtgprs
  };
}

function mapDispatchToProps() {
  return {}
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Map);
